package sf.dsl;

import sf.database.dialect.DBDialect;
import sf.database.dialect.DefaultDBDialect;
import sf.database.jdbc.sql.SQLContext;
import sf.database.jdbc.sql.SQLParameter;
import sf.database.support.DBMS;
import sf.dsl.example.ExampleSQL;
import sf.dsl.example.OffsetLimit;
import sf.dsl.example.OrderField;
import sf.dsl.example.ICondition;
import sf.dsl.example.ITable;
import sf.dsl.example.SQLFlag;
import sf.dsl.example.SimpleTable;
import sf.tools.ArrayUtils;
import sf.tools.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

public class DeleteDSL {
    public static final String currentOf = " CURRENT OF ";

    protected SQLFlag sqlFlag = new SQLFlag();
    /**
     * 查询条件是否必须添加表别名,默认false
     */
    protected AtomicBoolean mustTableAlias = new AtomicBoolean(false);
    protected List<SimpleTable> deleteTables;
    protected List<ITable> linkTables = new LinkedList<>();
    /**
     * from条件信息
     */
    protected List<ICondition> linkConditions = new LinkedList<>();
    /**
     * where条件信息
     */
    protected List<ICondition> whereConditions = new LinkedList<>();


    /**
     * 排序字段
     */
    protected List<OrderField> orderByList = new LinkedList<>();
    /**
     * 查询总数限制
     */
    protected OffsetLimit offsetLimit;

    protected DBDialect dialect = DefaultDBDialect.instance;

    public DeleteDSL(SimpleTable... deleteTables) {
        this.deleteTables = new LinkedList<>();
        if (ArrayUtils.isNotEmpty(deleteTables)) {
            Collections.addAll(this.deleteTables, deleteTables);
        }
    }

    public DeleteDSL addFlag(SQLFlag.Position position, String flag) {
        this.sqlFlag.addFlag(position, flag);
        return this;
    }

    public DeleteDSL mustTableAlias(boolean mustTableAlias) {
        this.mustTableAlias.set(mustTableAlias);
        return this;
    }

    public DeleteDSL linkTable(ITable... tables) {
        for (ITable t : tables) {
            linkTables.add(t);
        }
        mustTableAlias.set(true);
        return this;
    }

    public DeleteDSL linkConditions(Collection<ICondition> linkConditions) {
        this.linkConditions.addAll(linkConditions);
        mustTableAlias.set(true);
        return this;
    }

    public DeleteDSL linkConditions(ICondition... conditions) {
        if (ArrayUtils.isNotEmpty(conditions)) {
            Collections.addAll(linkConditions, conditions);
        }
        mustTableAlias.set(true);
        return this;
    }

    public DeleteDSL where(Collection<ICondition> whereConditions) {
        this.whereConditions.addAll(whereConditions);
        mustTableAlias.set(true);
        return this;
    }

    public DeleteDSL where(ICondition... conditions) {
        if (ArrayUtils.isNotEmpty(conditions)) {
            Collections.addAll(whereConditions, conditions);
        }
        return this;
    }

    public DeleteDSL orderByList(List<OrderField> orderByList) {
        this.orderByList = orderByList;
        return this;
    }

    public DeleteDSL offsetLimit(OffsetLimit offsetLimit) {
        this.offsetLimit = offsetLimit;
        return this;
    }

    public DeleteDSL setDialect(DBDialect dialect) {
        this.dialect = dialect;
        return this;
    }

    public SQLContext getSQLContext() {
        StringBuilder sql = new StringBuilder();
        List<SQLParameter> list = new ArrayList<>();
        SQLContext sqlContext = new SQLContext();
        sqlFlag.toSql(SQLFlag.Position.START, sql, list);
        sql.append("delete ");
        sqlFlag.toSql(SQLFlag.Position.AFTER_SELECT, sql, list);
        sql.append("from ");
        if (DBMS.mysql.getNumber() == dialect.getNumber() && deleteTables.size() > 1) {
            boolean b = false;
            for (SimpleTable deleteTable : deleteTables) {
                if (b) {
                    sql.append(',');
                }
                deleteTable.toOnlyAliasSql(sql, list, dialect);
                b = true;
            }
        } else {
            for (SimpleTable deleteTable : deleteTables) {
                deleteTable.toSql(sql, list, dialect);
                break;
            }
        }
        if (DBMS.mysql.getNumber() == dialect.getNumber()) {
            if (!linkTables.isEmpty() || !linkConditions.isEmpty()) {
                sql.append(" USING ");
            }
            boolean flag = false;
            for (ITable s : linkTables) {
                if (flag) {
                    sql.append(',');
                }
                s.toSql(sql, list, dialect);
                flag = true;
            }
            for (ICondition condition : linkConditions) {
                condition.toSql(sql, list, mustTableAlias, dialect);
            }
        } else if (DBMS.postgresql.getNumber() == dialect.getNumber()) {
            if (!linkTables.isEmpty() || !linkConditions.isEmpty()) {
                sql.append(" USING ");
            }
            if (!linkTables.isEmpty()) {
                boolean flag = false;
                for (ITable s : linkTables) {
                    if (flag) {
                        sql.append(',');
                    }
                    s.toSql(sql, list, dialect);
                    flag = true;
                }
            }
            for (ICondition condition : linkConditions) {
                condition.toSql(sql, list, mustTableAlias, dialect);
            }
        } else if (DBMS.sqlserver.getNumber() == dialect.getNumber()) {
            if (!linkTables.isEmpty()) {
                for (ITable s : linkTables) {
                    sql.append(',');
                    s.toSql(sql, list, dialect);
                }
            }
            for (ICondition condition : linkConditions) {
                condition.toSql(sql, list, mustTableAlias, dialect);
            }
        }
        StringBuilder temp = new StringBuilder();
        ExampleSQL.getSQLContextWhereClause(temp, list, whereConditions, mustTableAlias, dialect, false);
        String whereClause = temp.toString();
        if (StringUtils.isNotBlank(whereClause)) {
            sql.append(" where ").append(whereClause);
        }
        if (DBMS.mysql.getNumber() == dialect.getNumber() || DBMS.sqlite.getNumber() == dialect.getNumber()) {
            temp.delete(0, temp.length());
            ExampleSQL.getOrderByClause(temp, list, orderByList, mustTableAlias, dialect);
            String orderByCaluse = temp.toString();
            if (StringUtils.isNotBlank(orderByCaluse)) {
                sql.append(" order by ").append(orderByCaluse);
            }
            if (offsetLimit != null) {
                sql = ExampleSQL.buildLimitOffsetSql(sql, dialect, offsetLimit);
            }
        }
        sqlFlag.toSql(SQLFlag.Position.END, sql, list);
        sqlContext.setSql(sql.toString());
        sqlContext.setParas(list);
        return sqlContext;
    }
}
